package library.client.service.impl;

import library.client.domain.po.User;
import library.client.mapper.UsersMapper;
import library.client.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 
 *
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User> implements IUsersService {

    @Override
    public User getByUsername(String username) {
        User users = lambdaQuery().eq(User::getUsername, username).one();
        if (users == null) {
            throw new IllegalArgumentException(username + " 用户不存在");
        }
        return users;
    }

    @Override
    public Long login(String username, String password) {
        User users = getByUsername(username);
        if (!users.getPassword().equals(password)) {
            throw new IllegalArgumentException("密码错误");
        }
        return users.getId();
    }
    
    @Override
    @Transactional
    public Long register(User user) {
        try {
            log.info("检查用户名是否已存在: {}", user.getUsername());
            // 检查用户名是否已存在
            User existingUser = lambdaQuery().eq(User::getUsername, user.getUsername()).one();
            if (existingUser != null) {
                throw new IllegalArgumentException("用户名已存在");
            }
            
            log.info("检查电子邮箱是否已存在: {}", user.getEmail());
            // 检查电子邮箱是否已存在
            if (user.getEmail() != null && !user.getEmail().isEmpty()) {
                User emailExists = lambdaQuery().eq(User::getEmail, user.getEmail()).one();
                if (emailExists != null) {
                    throw new IllegalArgumentException("该电子邮箱已被注册");
                }
            }
            
            // 设置默认角色为普通用户
            user.setRole(1);
            
            // 设置name字段（必填），如果未提供则使用用户名
            if (user.getName() == null || user.getName().isEmpty()) {
                user.setName(user.getUsername());
            }
            
            // 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            user.setCreatedAt(now);
            user.setUpdatedAt(now);
            
            log.info("开始保存用户信息，用户名: {}, 姓名: {}", user.getUsername(), user.getName());
            // 保存用户信息
            boolean saved = save(user);
            if (!saved) {
                throw new RuntimeException("保存用户信息失败");
            }
            
            log.info("用户注册成功，ID: {}", user.getId());
            return user.getId();
        } catch (Exception e) {
            log.error("注册用户失败", e);
            throw e;
        }
    }
}
